//
//  GYMyViewController.m
//  GoodLuck
//
//  Created by apple on 2018/1/26.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//


static NSString *firstCellIdentifier = @"firstCellIdentifier";
static NSString *secondCellIdentifier = @"secondCellIdentifier";

#import "GYMyViewController.h"
#import "GYMyCell.h"
#import "GYMyHeadView.h"
#import "GYMyFirstSecondCell.h"
#import "GYMySecondCell.h"
#import "GYloginViewController.h"
#import "GYUser.h"
#import "GYRegisterViewController.h"
#import "GYUserInfo.h"
#import <UIImageView+WebCache.h>
#import "GYUserSetViewController.h"
#import "GYDisCardViewController.h"
#import "GYDistributionInfomationViewController.h"
#import "GYVIPApplyViewController.h"
#import "GYAddressViewController.h"
#import "GYPropertyViewController.h"
#import "GYIntegralViewController.h"
#import "GYShopCollectionViewController.h"
#import "GYUserFootViewController.h"
#import "GYOrderViewController.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYNetWorkTools.h"
#import "GYSystemMessageViewController.h"
#import "GYRefundListViewController.h"
#import "GYShopingCartViewController.h"
#import "GYPersonalInfoSetViewController.h"

@interface GYMyViewController ()<UITableViewDelegate,UITableViewDataSource,GYMyHeadViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/** 显示表格 */
@property (nonatomic, strong) UITableView *tableView;

/** 第三分区的标题数组 */
@property (nonatomic, strong) NSArray *threeArrays;

/** 表格头上图 */
@property (nonatomic, strong) GYMyHeadView *tableHeadView;

/** 登入界面显示 */
@property (nonatomic, strong) UIViewController *showViewControlelr;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

/** 用户个人信息 */
@property (nonatomic, strong) GYUserInfo *userInfo;

/**
 表示是否在我的界面
 */
@property (nonatomic, getter=isMyVC) BOOL myVC;
@end

@implementation GYMyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBColor(245, 245, 245);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(againLogin) name:userAgainLanding object:nil];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.myVC = YES;
    //1.首先判断用户有没有登入
    if ([GYUser loadUserInfo] != nil) {
        //1.隐藏导航栏
        self.navigationController.navigationBar.hidden = YES;
        [self setupUserInfoView];
        [self loadUserInfo];
    }else {
        //没有登陆这加载 登陆界面
        [self setupLoginView];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    self.navigationController.navigationBar.hidden = NO;
}

//重新加载页面
- (void)againLogin {
    if (self.tabBarController.selectedIndex == 2) {
        //在这里要判断是不是在我的页面
        BOOL isExtend = NO;
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isMemberOfClass:[GYloginViewController class]]) {
                isExtend = YES;
                break;
            }
        }
        if (!isExtend) {
            //初始化
            self.myVC = YES;
            //判断 有没有走过viewwillappear方法
            self.myVC = self.navigationController.viewControllers.count > 1 ? NO : YES ;
            [self setupLoginView];
        }
    }
}


- (void)setupUserInfoView {
    [self.tabBarController.tabBar setHidden:NO];
    //2.初始化表格
    [self setupUItableView];
    
    //IOS中去掉导航栏20个高度
    if (@available(iOS 11.0,*)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
}

- (void)setupLoginView {
    //判断loginVC存不存在
    if (self.showViewControlelr == nil) {
        
        CATransition *animation = [CATransition animation];
        animation.duration = 0.2;
        animation.timingFunction = UIViewAnimationCurveEaseInOut;
        animation.type = kCATransitionFade;//这里可以选择下面列举出来的几个动画，
        animation.subtype = kCATransitionFromTop;
        [[[[UIApplication sharedApplication] keyWindow] layer] addAnimation:animation forKey:nil];
        
        GYloginViewController *loginVC = [[GYloginViewController alloc] initWithNibName:@"GYloginViewController" bundle:nil];
        
        __weak typeof(self) weakSelef = self;
        loginVC.changedViewCallBack = ^ {
            //        [weakSelef.navigationController popViewControllerAnimated:YES];
            //1.显示底部工具栏
            weakSelef.tabBarController.tabBar.hidden = NO;
            
            //回到主界面
            weakSelef.tabBarController.selectedIndex = 0;
        };
        loginVC.loginViewRemoveFromSuperView = ^{
            weakSelef.showViewControlelr = nil;
            if (weakSelef.isMyVC) {
                //1.加载个人信息界面
                [weakSelef setupUserInfoView];
                
                //2.加载个人信息
                [weakSelef loadUserInfo];
                
                weakSelef.navigationController.navigationBar.hidden = YES;
            }else {
                NSLog(@"--------------------");
                weakSelef.navigationController.navigationBar.hidden= NO;
                weakSelef.tabBarController.tabBar.hidden = YES;
            }
            [weakSelef.navigationController popViewControllerAnimated:YES];
        };
        self.showViewControlelr = loginVC;
        
        //跳转
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}



- (void)loadUserInfo {
    [self.tableView.mj_header endRefreshing];
    //3.加载个人信息
    [GYUserInfo loadUserInfo:^(GYUserInfo * _Nullable userInfo, NSError * _Nullable error) {
        if (error) {
            NSLog(@"loadUserInfoFailed=====%@",error);
        }else {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            //刷新个人信息
            self.userInfo = userInfo;
            self.tableHeadView.collectionLable.text = [NSString stringWithFormat:@"%d",userInfo.favorites_goods];
            self.tableHeadView.shopCollectionLbale.text = [NSString stringWithFormat:@"%d",userInfo.favorites_store];
            //由于后台返回的 url地址全部都是一样的  设置图片之前应该清楚缓存中的这张图
            [[SDImageCache sharedImageCache] removeImageForKey:userInfo.avator withCompletion:^{
                //设置图片
                [self.tableHeadView.headImageView sd_setImageWithURL:userInfo.avatorURL placeholderImage:[UIImage imageNamed:@"ff_icon4-1"]];
            }];
            self.tableHeadView.userNameLable.text = userInfo.member_name;
            self.tableHeadView.userLevelLable.text = userInfo.level_name;
            
            [self.tableView reloadData];
            
        }
    }];
}

- (void)setupUItableView {
    if (self.tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-(iPhoneX ? 83: 44)) style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.sectionFooterHeight = 10;
        tableView.sectionHeaderHeight = 0;
        tableView.backgroundColor = RGBColor(245, 245, 245);
        
        [self.view addSubview:tableView];
        self.tableView = tableView;
        
        GYMyHeadView *headView = [[[NSBundle mainBundle] loadNibNamed:@"GYMyHeadView" owner:nil options:nil] firstObject];
        headView.delegate = self;
        headView.frame = CGRectMake(0, 0, ScreenWidth, [headView getViewHeight]);
        tableView.tableHeaderView = headView;
        self.tableHeadView = headView;
        
        //注册cell
        [tableView registerClass:[GYMyFirstSecondCell class] forCellReuseIdentifier:firstCellIdentifier];
        [tableView registerClass:[GYMySecondCell class] forCellReuseIdentifier:secondCellIdentifier];
        
        //添加上拉刷新
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadUserInfo)];
    }
}


#pragma mark -- <UITableViewDelegate,UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
            break;
            
        case 1:
            return 2;
            break;
            
        case 2:
            return self.threeArrays.count;
            break;
        }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section ==0) {
        if (indexPath.row == 0) {
            GYMyCell *cell = [GYMyCell cellWithTableView:tableView];
            
            cell.headLable.text = @"我的订单";
            cell.footLable.text = @"查看全部订单";
            cell.titleImage.image = [UIImage imageNamed:@"mc_01"];
            
            return cell;
        }else {
            GYMyFirstSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:firstCellIdentifier];
            cell.userInfo = self.userInfo;
            cell.allOrderBlock = ^(NSInteger tag) {
                
                if (tag < 5) {
                    GYOrderViewController *orderVC = [[GYOrderViewController alloc] initWithNibName:@"GYOrderViewController" bundle:nil];
                    orderVC.hidesBottomBarWhenPushed = YES;
                    orderVC.currentSelectIndex = tag+1;
                    [self.navigationController pushViewController:orderVC animated:YES];
                }else {
                    GYRefundListViewController *refunListVC = [[GYRefundListViewController alloc] initWithNibName:@"GYRefundListViewController" bundle:nil];
                    refunListVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:refunListVC animated:YES];

                }
            };
            
            return cell;
        }
    }else if (indexPath.section ==1) {
        if (indexPath.row == 0) {
            GYMyCell *cell = [GYMyCell cellWithTableView:tableView];
            
            cell.headLable.text = @"我的财产";
            cell.footLable.text = @"查看全部财产";
            cell.titleImage.image = [UIImage imageNamed:@"mc_02"];
            
            return cell;
        }else {
            GYMySecondCell *cell = [tableView dequeueReusableCellWithIdentifier:secondCellIdentifier];
            cell.detailBlock = ^(NSInteger tag){
                //回调
                GYIntegralViewController *integraVC = [[GYIntegralViewController alloc] initWithNibName:@"GYIntegralViewController" bundle:nil];
                integraVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:integraVC animated:YES];
            };
            
            return cell;
        }

    }else {
        GYMyCell *cell = [GYMyCell cellWithTableView:tableView];
        
        cell.headLable.text = self.threeArrays[indexPath.row];
        cell.footLable.text = @"";
//        if (indexPath.row == 4) {
//            cell.titleImage.image = [UIImage imageNamed:@"mc_04"];
//        }else {
        cell.titleImage.image = [UIImage imageNamed:indexPath.row == 0 ? @"mc_03" : @"ic_mine_small_setting"];
//        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                GYOrderViewController *orderVC = [[GYOrderViewController alloc] initWithNibName:@"GYOrderViewController" bundle:nil];
                orderVC.hidesBottomBarWhenPushed = YES;
                orderVC.currentSelectIndex = 1;
                [self.navigationController pushViewController:orderVC animated:YES];
            }
        }
            break;
            
        case 1:
        {
            if (indexPath.row == 0) {
                GYPropertyViewController *propertVC = [[GYPropertyViewController alloc] initWithNibName:@"GYPropertyViewController" bundle:nil];
                propertVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:propertVC animated:YES];
            }
        }
            break;
            
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                {
                    GYAddressViewController *addressVC = [[GYAddressViewController alloc] init];
                    addressVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:addressVC animated:YES];

                }
                    break;
                    
                case 1:
                {
                    GYPersonalInfoSetViewController *personalInfoVC = [[GYPersonalInfoSetViewController alloc] initWithNibName:@"GYPersonalInfoSetViewController" bundle:nil];
                    personalInfoVC.member_name = self.userInfo.member_name;
                    personalInfoVC.member_mobile = self.userInfo.member_mobile;
                    personalInfoVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:personalInfoVC animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
            
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        return 60;
    }
    
    if (indexPath.section == 1 && indexPath.row == 1) {
        return 60;
    }
    
    return 44;
}


#pragma mark -- 通知显示登入界面
- (void)showLoginView {
    NSLog(@"加载登陆界面....");
    [self setupLoginView];
}

#pragma mark - - GYMyHeadViewDelegate

- (void)headViewToBtuClick:(NSInteger)tag {
    switch (tag) {
        case 1:
        {
            GYUserSetViewController *setVC = [[GYUserSetViewController alloc] initWithNibName:@"GYUserSetViewController" bundle:nil];
            setVC.currentPhone = self.userInfo.member_mobile;
            setVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:setVC animated:YES];
        }
            break;
            
        case 2:
        {
            GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
            __weak typeof(self) weakSelf = self;
            basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
                switch (index) {
                    case 0:
                    {
                        weakSelf.tabBarController.selectedIndex = 0;
                        [weakSelf.tabBarController.tabBar setHidden:NO];
                    }
                        break;
                        
                    case 1:
                    {
                        GYShopingCartViewController *shopingCartVC = [[GYShopingCartViewController alloc] initWithNibName:@"GYShopingCartViewController" bundle:nil];
                        [weakSelf.navigationController pushViewController:shopingCartVC animated:YES];
                    }
                        break;
                        
                    case 2:
                    {
                        GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                        systemMessageVC.hidesBottomBarWhenPushed = YES;
                        [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];
                    }
                        break;
                        
                    case 3:
                    {
                        [GYNetWorkTools requestUserSignOut:^(NSDictionary *obj) {
                            //NSLog(@"obj ==== %@",obj);
                            int code = [[obj objectForKey:@"code"] intValue];
                            id datas = [obj objectForKey:@"datas"];
                            if (code == 200) {
                                //1.删除个人用户信息
                                [GYUser removeUserInfo];
                                //更换界面
                                weakSelf.tabBarController.selectedIndex = 0;
                                
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                            
                            }else if(code == 400){
                                NSLog(@"安全退出 出现错误===%@",[datas objectForKey:@"error"]);
                                [EasyTextView showText:@"安全退出失败,请稍后在尝试!"];
                            }
                        } error:^(NSError *error) {
                            [EasyTextView showText:@"安全退出失败,请稍后在尝试!"];
                            NSLog(@"用户安全退出出错...");
                        }];
                    }
                        break;
                        
                    default:
                        break;
                }
            };
            basePopoverVC.titles = @[@"首页",@"购物车",@"消息",@"注销"];
            basePopoverVC.images = @[@"home_w",@"ff_icon3",@"message_w",@"logoutbtn_w"];
            
            self.animationDelegate = [[PopoverAnimation alloc] init];
            self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 50, widthScale(130, iphone6_W), basePopoverVC.titles.count*50);
            basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
            
            basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
            [self presentViewController:basePopoverVC animated:YES completion:nil];
            
        }
            break;
            
            
        case 3:
        {
            GYShopCollectionViewController *shopColectionVC = [[GYShopCollectionViewController alloc] init];
            shopColectionVC.hidesBottomBarWhenPushed = YES;
            shopColectionVC.defaultIndex = 0;
            [self.navigationController pushViewController:shopColectionVC animated:YES];
        }
            break;
            
            
        case 4:
        {
            GYShopCollectionViewController *shopColectionVC = [[GYShopCollectionViewController alloc] init];
            shopColectionVC.hidesBottomBarWhenPushed = YES;
            shopColectionVC.defaultIndex = 1;
            [self.navigationController pushViewController:shopColectionVC animated:YES];
        }
            break;
            
            
        case 5:
        {
            GYUserFootViewController *footVC = [[GYUserFootViewController alloc] initWithNibName:@"GYUserFootViewController" bundle:nil];
            footVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:footVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)changedHeadImage {
    NSLog(@"修改用户头像...");
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请选择修改方式!" preferredStyle: UIAlertControllerStyleActionSheet];
    
    //1.获取系统支持的媒体格式
    NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    //2.创建系统相册对象
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    //3.设置代理
    ipc.delegate = self;
    //4.设置你要支持的媒体类型
    ipc.mediaTypes = @[[mediaTypes firstObject]];
    
    UIAlertAction *photot = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //5.判断设备支不支持这个种格式
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //6.设置你的数据来源
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:ipc animated:YES completion:nil];
        }
        
    }];
    UIAlertAction *MobileAlbum = [UIAlertAction actionWithTitle:@"手机相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //5.判断设备支不支持这个种格式
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            //6.设置你的数据来源
            ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:ipc animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertController addAction:photot];
    [alertController addAction:MobileAlbum];
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -- <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *selectImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImageJPEGRepresentation(selectImage, 0.1);
    //把图片上传  并且修改图片
    [GYNetWorkTools requestModfyUserHeadImage:imageData success:^(NSDictionary *obj) {
        //NSLog(@"obj ========  %@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        if (code == 200) {
            [EasyTextView showText:@"修改头像成功!"];
            //上传头像成功  更换头像
            self.tableHeadView.headImageView.image = selectImage;
        }else {
            [EasyTextView showText:@"修改头像失败,请稍后尝试!"];
            NSLog(@"error==========%@",[[obj objectForKey:@"datas"] objectForKey:@"error"]);
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"修改头像失败,请稍后尝试!"];
        NSLog(@"oploadHeadImage=====%@",error);
    }];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 懒加载

- (NSArray *)threeArrays {
    if (!_threeArrays) {
        _threeArrays = @[@"收货地址管理",@"用户设置"];
    }
    return _threeArrays;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:showLoginView object:nil];
    NSLog(@"GYMyViewController===dealloc");
}







@end
